<template>
	<view class="container">
		<view class="calc display titleAre themeBgColor topFixed" v-if="isHaveData">
			<text @click="editorClick">{{editorTxt}}</text>
		</view>
		<block v-if="isHaveData">
			<cart :shopCartList="shopCartList" @selectshop="selectshop" @selectgoods="selectgoods" @modifyNumber="modifyNumber" @inputChange="inputChange" class="cart"></cart>
		</block>
		<view class="noData" v-else>
			<noData :noDataType="noDataType"></noData>
		</view>
		<view class="display flow recommendAre">
			<view class="line"></view>
			<text>为你推荐</text>
			<view class="line"></view>
		</view>
		<view class="goodsAre" :style="{'margin-bottom': (isHaveData?'100rpx':'0')}">
			<goodsAre :goodsType="goodsType" :goodsList="goodsList"  @goodsClick="goodsClick"></goodsAre>
		</view>
		<uni-popup ref="showtip" :mask-click="false" :type="popType" @change="change">
			<loginPop class="pop" @cancel="cancel"></loginPop>
		</uni-popup>
		<settlementAre :total="total.toFixed(2)" :isAllCheck="isAllCheck" :isEditor="isEditor" @allCheck="allCheck" @deleteSelectBtn="deleteSelectBtn" @emptyFailureBtn="emptyFailureBtn" @goBuy="goBuy" v-if="isHaveData" class="settlement"></settlementAre>
	</view>
</template>

<script>
	import util from '@/common/util.js'
	import cart from '@/components/cart.vue'
	import settlementAre from '@/components/settlementAre.vue'
	import goodsAre from '@/components/goodsAre.vue'
	import noData from '@/components/noData.vue'
	import loginPop from '@/components/loginPop.vue'
	import {mapState} from 'vuex'
	export default {
		components: {cart,settlementAre,goodsAre,noData,loginPop},
		data() {
			return {
				shopCartList: [],
				goodsList: [],
				total: 0,
				isAllCheck: false,
				isEditor: false,
				goodsType: 'car',
				isHaveData: false,
				noDataType: 'car',
				popType: '',
			}
		},
		onLoad() {
			this.getGoods()
		},
		onShow() {
			this.getData()
		},
		computed:{
			...mapState(['hasLogin']),
			editorTxt(){
				let text = this.isEditor?'完成':'编辑'
				return text
			}
		},
		methods:{
			getData(){
				if(this.hasLogin){
					util.getAjax(this.global.apiUrl + '/get_user_supplier_product_buycar',this.getCartData,{user_id: this.$store.state.userId})
				}
			},
			getCartData(res){
				console.log(res)
				var that = this
				if(res.data.length != 0){
					for(let i in res.data){
						res.data[i].isCheck = false
						for(let j in res.data[i].items){
							res.data[i].items[j].sku_list = JSON.parse(res.data[i].items[j].sku_list)
							res.data[i].items[j].isCheck = false
							res.data[i].items[j].isFailure = res.data[i].items[j].status == 0?false:true//是否失效
							res.data[i].items[j].isSoldOut = res.data[i].items[j].sku_list.num != 0?false:true//是否售罄
						}
					}
					// console.log(res.data)
					if(that.shopCartList){
						let list = that.shopCartList
						let total = 0
						for(let i in list){
							if(list[i].isCheck){
								res.data[i].isCheck = true
							}
							for(let j in list[i].items){
								if(list[i].items[j].isCheck && !list[i].items[j].isFailure && !list[i].items[j].isSoldOut){
									for(let z in res.data){
										for(let h in res.data[z].items){
											if(list[i].items[j].id == res.data[z].items[h].id){
												res.data[z].items[h].isCheck = true
												total += util.calculate(res.data[z].items[h].price,res.data[z].items[h].num)
											}
										}
										total += Number(res.data[z].shop_content.freight?res.data[z].shop_content.freight:0)
									}
								}
							}
						}
						if(total != 0){
							that.total = total
						}
					}
					var isAllCheck = true
					for(let z in res.data){
						for(let h in res.data[z].items){
							if(!res.data[z].items[h].isCheck && res.data[z].items[h].status == 0){
								isAllCheck = false
								break;
							}
						}		
					}
					that.isHaveData = true,
					that.shopCartList = res.data,
					that.isAllCheck = isAllCheck
				}else{
					that.isHaveData = false,
					that.shopCartList = [],
					that.total = 0
				}
			},
			//选择商户
			selectshop(id){
				var that = this
				var list = that.shopCartList;
				for(let i in list){
					if(list[i].supplier_id == id){
						let isAdd = true
						for(let j in list[i].items){
							if(!list[i].items[j].isFailure && !list[i].items[j].isSoldOut){ 
								if(list[i].isCheck){
									//已选择
									isAdd = false
									if(list[i].items[j].isCheck){
										that.total -= util.calculate(list[i].items[j].price,list[i].items[j].num)
									}
									list[i].items[j].isCheck= false
								}else{
									//未选择
									isAdd = true
									if(!list[i].items[j].isCheck){
										that.total += util.calculate(list[i].items[j].price,list[i].items[j].num)
									}
									list[i].items[j].isCheck= true
								}
							}
						}
						list[i].isCheck = !list[i].isCheck
						if(isAdd){
							that.total += Number(list[i].shop_content.freight?list[i].shop_content.freight:0)
						}else{
							that.total -= Number(list[i].shop_content.freight?list[i].shop_content.freight:0)
						}
					}
				}
				var isAllCheck = true
				for(let i in list){
					for(let j in list[i].items){
						if(!list[i].items[j].isCheck && list[i].items[j].status == 0 && list[i].items[j].sku_list.num){
							isAllCheck = false
							break;
						}
					}
				}
				that.isAllCheck = isAllCheck
				that.shopCartList = list
			},
			//选择商品
			selectgoods(id){
				var that = this
				var list = that.shopCartList;
				for(let i in list){
					let isAdd = true
					let isOtherCheck = false
					let otherCheckList = []
					let otherUnCheckList = []
					let index = 0
					for(let j in list[i].items){
						if(list[i].items[j].product_id == id && !list[i].items[j].isFailure && !list[i].items[j].isSoldOut){
							if(list[i].items[j].isCheck){
								//已选择
								isAdd = false
								that.total -= util.calculate(list[i].items[j].price,list[i].items[j].num)
								if(that.isAllCheck){
									that.isAllCheck = false
								}
							}else{
								//未选择
								isAdd = true
								that.total += util.calculate(list[i].items[j].price,list[i].items[j].num)
							}
							list[i].items[j].isCheck= !list[i].items[j].isCheck
						}
						index ++ 
						if(list[i].items[j].isCheck){
							isOtherCheck = true
							otherCheckList.push(list[i].items[j])
						}else{
							isOtherCheck = false
							otherUnCheckList.push(list[i].items[j])
						}
					}
					if(!isOtherCheck){
						if(index == otherUnCheckList.length){
							that.total -= Number(list[i].shop_content.freight?list[i].shop_content.freight:0)
						}else{
							if(isAdd){
								let isOtherChecked = false
								for(let k in otherCheckList){
									if(otherCheckList[k].product_id != id){
										isOtherChecked = true
									}
								}
								if(!isOtherChecked){
									that.total += Number(list[i].shop_content.freight?list[i].shop_content.freight:0)
								}
							}
						}
					}
				}
				var isAllCheck = true
				for(let i in list){
					let isShopAll = true
					for(let j in list[i].items){
						if(!list[i].items[j].isCheck && !list[i].items[j].isFailure && !list[i].items[j].isSoldOut ){
							isAllCheck = false
							isShopAll = false
							break;
						}
					}
					list[i].isCheck = isShopAll
				}
				that.isAllCheck = isAllCheck
				that.shopCartList = list
				// console.log(list);
			},
			//增减数量
			modifyNumber(arr){
				console.log(arr)
			    var that = this
			    var list = that.shopCartList
				var type = arr[0]
				var id = arr[1]
			    for(let i in list){
					console.log(list)
					for(let j in list[i].items){
						if(list[i].items[j].id == id && !list[i].items[j].isFailure && !list[i].items[j].isSoldOut ){
							switch (type) {
								case 'plus':
									list[i].items[j].num ++
									break;
								case 'minus':
									list[i].items[j].num --
									break;
							}
							console.log(list)
							util.getAjax(this.global.apiUrl +'/operation_user_supplier_product_buycar',function(res){
								console.log(res)
								if(res.data.code == 1){
									//获取购物车数据
									that.getData()
								}
							},{type: 2,
							id: list[i].items[j].id,
							num: list[i].items[j].num,
							price: list[i].items[j].price,
							product_id: list[i].items[j].id,
							supplier_id: list[i].supplier_id})
						}	
					}
			    }
			},
			inputChange(value,id){
				var that = this
				var list = that.shopCartList
				for(let i in list){
					console.log(list)
					for(let j in list[i].items){
						if(list[i].items[j].id == id && !list[i].items[j].isFailure && !list[i].items[j].isSoldOut ){
							util.getAjax(that.global.apiUrl +'/operation_user_supplier_product_buycar',function(res){
								console.log(res)
								if(res.data.code == 1){
									//获取购物车数据
									that.getData()
								}
							},{type: 2,
							id: list[i].items[j].id,
							num: value,
							price: list[i].items[j].price,
							product_id: list[i].items[j].id,
							supplier_id: list[i].supplier_id})
						}	
					}
				}
			},
			//编辑按钮
			editorClick(){
				this.isEditor = !this.isEditor
			},
			//全选
			allCheck(){
			    var that = this
			    var list = that.shopCartList
			    for(var i in list){
					for(let j in list[i].items){
						if(!list[i].items[j].isFailure && !list[i].items[j].isSoldOut ){
							if(that.isAllCheck){
								//已经全选
								list[i].isCheck = false
								list[i].items[j].isCheck = false
								that.total = 0
							}else{
								//没有全选
								list[i].isCheck = true
								list[i].items[j].isCheck = true
								that.total += util.calculate(list[i].items[j].price,list[i].items[j].num)
							}
						}
					}
					if(!that.isAllCheck){
						that.total += Number(list[i].shop_content.freight?list[i].shop_content.freight:0)
					}
			    }
				that.isAllCheck = !that.isAllCheck
			    that.shopCartList = list
			},
			//删除选择的商品
			deleteSelectBtn(){
			    var that = this
			    var list = that.shopCartList
			    var idList = []
			    for(var i in list){
					for(let j in list[i].items){
						if(list[i].items[j].isCheck){
						  idList.push(list[i].items[j].id)        
						}
					}
			    }
			    if(idList.length != 0){
					idList = JSON.stringify(idList)
					util.showModalAll('删除商品','您是否确定删除所选商品？',function(){
						util.getAjax(that.global.apiUrl +'/operation_user_supplier_product_buycar',function(res){
							console.log(res);
							if(res.data.code == 1){
								  util.showToast('none','已删除');
								  that.shopCartList = []
								  that.getData()
							}
						},{type: 3,id: idList})
					})
			    }else{
					util.showToast('none','请选择您需要删除的商品')
			    }
			},
			//清空失效产品
			emptyFailureBtn(){
			    var that = this
			    var list = that.shopCartList
			    var idList = []
			    for(var i in list){
					for(let j in list[i].items){
						if(list[i].items[j].status == 1 || list[i].items[j].sku_list.num == 0 ){
							idList.push(list[i].items[j].id)        
						}
					}
			    }
			    if(idList.length != 0){
					idList = JSON.stringify(idList)
					util.showModalAll('删除失效商品','您是否确定删除失效商品？',function(){
						util.getAjax(that.global.apiUrl +'/operation_user_supplier_product_buycar',function(res){
							// console.log(res);
							if(res.data.code == 1){
								util.showToast('none','已删除');
								//获取购物车数据
								that.shopCartList = []
								that.getData()
							}
						},{type: 3,id: idList})
					})
			    }else{
					util.showToast('none','暂无失效商品')
			    }
			},
			getGoods(){
				util.getAjax(this.global.apiUrl + '/get_tj_ten',(res)=>{
					console.log(res)
					if(res.data.length!=0){
						this.goodsList = res.data
					}
				})
			},
			goodsClick(id){
				uni.navigateTo({
					url: '/subPackages/goods/goodsDetails/goodsDetails?id='+ id,
				})
			},
			togglePopup(type,open) {
				this.popType = type
				this.$nextTick(() => {
					this.$refs['show' + open].open()
				})
			},
			cancel(type){
				this.$refs['show' + type].close()
			},
			change(e) {
				console.log('是否打开:' + e.show)
			},
			goBuy(){
				if(this.hasLogin){
					if(this.total != 0){
						var list = this.shopCartList
						var buyList = []
						// console.log(list);
						for(var i in list){
							let goodsList = []
							let subtotal = 0
							let totalNum = 0
							for(let j in list[i].items){
								if(list[i].items[j].isCheck && !list[i].items[j].isFailure && !list[i].items[j].isSoldOut){
									subtotal += util.calculate(list[i].items[j].price,list[i].items[j].num)
									totalNum += Number(list[i].items[j].num)
									goodsList.push(list[i].items[j])
								}
							}
							// console.log(goodsList);
							if(goodsList.length != 0){
								list[i].subtotal = subtotal.toFixed(2)
								list[i].totalNum = totalNum
								list[i].items = goodsList
								buyList.push(list[i])
							}
						}
						// console.log(buyList)
						uni.navigateTo({
							url: '/subPackages/goods/submitOrders/submitOrders?list=' + encodeURIComponent(JSON.stringify(buyList)) + '&type=' + 2 + '&total=' + this.total 
						})
						this.shopCartList = []
						this.total = 0
					}else{
						util.showToast('none','您暂未选择商品，请选择商品后重新支付')
					}
				}else{
					this.togglePopup('center','tip')
				}
			}
		},
		onUnload() {
			
		},
		onPullDownRefresh: function () {
		    var that = this
			that.getData()
			that.getGoods()
		    uni.stopPullDownRefresh();
		},
	}
</script>

<style lang="scss">
	@import '@/common/css/shopCar.scss';
	.noData{
		@include backG;
	}
</style>
